<?php

namespace App\Http\Controllers\Logic;

use App\Http\Controllers\Controller;
use App\Model\OADept;
use App\Model\OAPosition;
use App\Model\OAPositionAuth;
use App\Model\OAStaff;
use App\Model\OAStaffDept;
use App\Model\OAStaffPosition;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use phpDocumentor\Reflection\Types\Boolean;

class StaffLogic extends Controller
{
    private $state_list = ['离职','正常','待离职'];
    private $sex_list = [1=>'男',2=>'女',3=>'保密'];
    //获取员工列表
    public function getStaffList(Request $request)
    {

        try {
           $staff_list = OAStaff::query()
           ->when($account= $request->input('account',''),function ($q) use ($account){
               return $q->where('account', 'like', '%' . $account . '%');
           })
           ->select('*')
           ->get()
           ->toArray();
            foreach ($staff_list as &$staff){
                //修改状态
                $staff['status'] = $this->state_list[$staff['status']];
                $roleList = explode(',',$staff['roleid']);
                $positionList = OAPosition::query()->whereIn('id',$roleList)->pluck('title')->toArray();
                $staff['position'] = implode(',',$positionList);
                $deptList = explode(',',$staff['deptid']);
                $deptList = OADept::query()->whereIn('id',$deptList)->pluck('title')->toArray();
                $staff['dept'] = implode(',',$deptList);
                unset($staff['position_id'],$staff['deptid']);
            }

            return [
                'data'=>$staff_list,
                'total'=>count($staff_list),
                'state_list'=>$this->state_list,
            ];
        }catch(\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }

    //批量删除
    public function BatchDelete($input)
    {
        $query = OAStaff::query();
        try{
            return  $query->whereIn('id',$input['id_list'])->delete();
        }catch(\Exception $e){
            throw new \Exception($query->toSql());
        }
    }

    //获取员工详情
    public function getStaffInfo($input)
    {
        $info = OAStaff::query()->where('id',$input['id'])->first();

        if(is_null($info)) throw new \Exception('员工不存在,请检查');

        $logic = new CommonLogic();

        $common_list = $logic->getCommonData(['dept','position']);
        //获取员工部门
        //$this->getStaffDeptList($info);
        //获取员工职位
        //$this->getStaffPositionList($info);
        $roleid = explode(',',$info->roleid);
        $deptid = explode(',',$info->deptid);
        $info->roleid =  array_map(function ($item) {
            return intval($item);
        },$roleid);
        $info->deptid =  array_map(function ($item) {
            return intval($item);
        },$deptid);
        //格式化部门,职位
        $info->dept_list = $common_list['dept'];
        $info->position_list = $common_list['position'];
        $info->identify = intval($info->identify);

        return $info;


    }

    //查员工部门
    private function getStaffDeptList(&$staff)
    {
        $dept_ids = explode(',',$staff->deptid);
        $staff->dept_list = OADept::query()->whereIn('id',$dept_ids)->where('status',1)->pluck('title');
    }

    //获取员工职位
    public function getStaffPositionList(&$staff)
    {
        $position_ids = explode(',',$staff->roleid);
        $staff->position_list = OAPosition::query()->whereIn('id',$position_ids)->where('status',1)->pluck('title');
    }

    //获取员工权限
    public function getStaffAuthList($position_list) :array
    {
            $auth_list = [];
        foreach ($position_list as $position){
            $position_info_list = OAPositionAuth::query()->where('position_id',$position['id'])->get();
            $temp = [];
            foreach ($position_info_list as $position_info) {
                $authInfo = $position_info->getPositionAuth()->where('state',1)->get();
                if(!$authInfo->isEmpty()){
                    $temp[] = ['id'=>$authInfo[0]->id,'title'=>$authInfo[0]->title];
                }
            }
            $auth_list[$position['id']] = array_column($temp,null,'id');
            unset($temp);
                }
        return $auth_list;
    }

    //格式化部门
    private function formatList($list, $dept) :array
    {
        //dd($list);
        $id_arr = array_column($dept,'id');
        foreach ($list as $k => $item)
        {
            $list[$k]['checked'] = in_array($item['id'],$id_arr);
        }
        return $list;
    }

    //更新员工信息
    public function staffEdit($input) :bool
    {
        DB::beginTransaction();
        try {
            //if(!is_id_card($input['id_card'])) throw new \Exception('身份证非法');
            $staff = OAStaff::query()->where('id', $input['id'])->first();
            if(isset($input['password']) && isset($input['repeatPassword'])){
                if($input['password'] != $input['repeatPassword']) throw new \Exception('两次密码不一致');
                $staff->password = md5($input['password']);
            }
            if(OAStaff::query()->where('account',$input['account'])->where('id','<>',$input['id'])->exists()) throw new \Exception('账号重复');
            $staff->account = $input['account'];
            $staff->username = $input['username'];
            $staff->phone = $input['phone'];
            $staff->email = $input['email'];
            $staff->sex = $input['sex'];
            $staff->status = $input['status'];
            $staff->id_card = $input['id_card'];
            $staff->avatar = $input['avatar'];
            $staff->address = $input['address'];
            $staff->roleid = implode(',',$input['roleid']);
            $staff->deptid = implode(',',$input['deptid']);
            $staff->save();

           DB::commit();
           return true;
        }catch(\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }


    public function StaffPositionRole($input): array
    {
        $info = OAStaff::query()->where('id',$input['id'])->first();
        //获取员工部门
        $response['dept_list'] =  OADept::query()->where('status','!=',0)->whereIn('id',explode(',',$info->deptid))->select(['id','title'])->get()->toArray();
        $response['position_list'] =  OAPosition::query()->where('status','!=',0)->whereIn('id',explode(',',$info->roleid))->select(['id','title'])->get()->toArray();
        return $response;
    }



}
